package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.WaterPriceCalculator;
import com.ruoyi.system.domain.WaterBill;
import com.ruoyi.system.domain.WaterMeter;
import com.ruoyi.system.domain.WaterUser;
import com.ruoyi.system.domain.vo.BillGenerateResult;
import com.ruoyi.system.domain.vo.BillingCycle;
import com.ruoyi.system.service.IRevenueService;
import com.ruoyi.system.service.IWaterBillService;
import com.ruoyi.system.service.IWaterMeterService;
import com.ruoyi.system.service.IWaterUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @description 营收服务实现类
 * @data 2025/9/23 13:43
 */
@Service
public class RevenueServiceImpl implements IRevenueService {

    @Autowired
    private IWaterUserService userService;

    @Autowired
    private IWaterMeterService waterMeterService;

    @Autowired
    private IWaterBillService waterBillService;

    @Override
    public BillGenerateResult generateUserBills(String userId, String billingDate) {
        BillGenerateResult result = new BillGenerateResult();
        List<WaterBill> generatedBills = new ArrayList<>();
        try {
            // 获取用户信息
            WaterUser user = userService.selectWaterUserByUserId(userId);
            if (user == null) {
                result.setSuccess(false);
                result.setMessage("用户不存在");
                return result;
            }

            // 获取用户的所有水表
            WaterMeter waterMeter = new WaterMeter();
            waterMeter.setUserId(userId);
            List<WaterMeter> meters = waterMeterService.selectWaterMeterList(waterMeter);
            if (meters.isEmpty()) {
                result.setSuccess(false);
                result.setMessage("用户没有可用的水表");
                return result;
            }

            // 为每个水表生成账单
            for (WaterMeter meter : meters) {
                WaterBill bill = generateSingleBill(meter, billingDate);
                if (bill != null) {
                    generatedBills.add(bill);
                }
            }
            result.setSuccess(true);
            result.setWaterBills(generatedBills);
            result.setMessage(String.format("成功生成%d张账单", generatedBills.size()));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("生成账单失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 为单个水表生成账单
     */
    private WaterBill generateSingleBill(WaterMeter meter, String billingDate) {
        // 获取计费周期
        BillingCycle cycle = calculateBillingCycle(meter, billingDate);
        if (cycle == null) {
            return null;
        }

        // 获取用水量
        BigDecimal usageAmount = getUsageAmount(meter, cycle);
        if (usageAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return null; // 无用水量不生成账单
        }

        // 计算水费
        String priceCode = meter.getPriceCode();
        WaterPriceCalculator.WaterFeeDetail feeDetail = WaterPriceCalculator.getWaterFeeDetail(
                WaterPriceCalculator.getWaterPrice(priceCode), usageAmount.doubleValue());

        // 创建账单
        WaterBill bill = new WaterBill();
//        bill.setBillNumber(generateBillNumber());
        bill.setUserId(meter.getUserId());
        bill.setMeterNo(meter.getMeterNo());
        bill.setBillingDate(DateUtils.getNowDate());
        bill.setBillingCycleStart(cycle.getStartDate());
        bill.setBillingCycleEnd(cycle.getEndDate());
        bill.setUsageAmount(usageAmount.doubleValue());
//        bill.setUnitPrice(feeDetail.get());
        BigDecimal totalFee = new BigDecimal(feeDetail.getTotalFee());
        bill.setTotalAmount(feeDetail.getTotalFee());
        bill.setAmountDue(totalFee);
//        bill.setDueDate(billingDate.plusDays(15)); // 默认15天后截止
        bill.setBillStatus(1); // 未支付
        // 保存账单
        waterBillService.insertWaterBill(bill);
        return bill;
    }

    private BillingCycle calculateBillingCycle(WaterMeter meter, String billingDate) {
        BillingCycle cycle = new BillingCycle();
        cycle.setStartDate(DateUtils.parseDate("2025-08-25"));
        cycle.setEndDate(DateUtils.parseDate("2025-09-25"));
        return cycle;
    }
    private BigDecimal getUsageAmount(WaterMeter meter, BillingCycle cycle) {
        // 获取用户用水量
        BigDecimal usageAmount = new BigDecimal(100);
        return usageAmount;
    }
}
